package top.z.work.framework.common.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 获取真实地址
 * // {
 * //     "ip": "27.227.164.240",
 * //     "pro": "甘肃省",
 * //     "proCode": "620000",
 * //     "city": "兰州市",
 * //     "cityCode": "620100",
 * //     "region": "",
 * //     "regionCode": "0",
 * //     "addr": "甘肃省兰州市 电信",
 * //     "regionNames": "",
 * //     "err": ""
 * // }
 */

@Slf4j
public class IpAddressUtil {
    // 实时查询
    public static final String ADDRESS_URL = "https://whois.pconline.com.cn/ipJson.jsp";
    public static final String UNKNOWN     = "未知";

    public static String getAddress(String ip) {
        // 内网
        if (IpUtil.internalIp(ip)) {
            return "内网IP";
        }
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("ip", ip);
            paramMap.put("json", true);
            String response = HttpUtil.get(ADDRESS_URL, paramMap);
            if (StrUtil.isBlank(response)) {
                log.error("根据IP获取地址异常 {}", ip);
                return UNKNOWN;
            }

            Address address = JsonUtil.parseObject(response, Address.class);
            return String.format("%s %s", address.getPro(), address.getCity());
        } catch (Exception e) {
            log.error("根据IP获取地址异常 {}", ip);
        }

        return UNKNOWN;
    }

    @Data
    static class Address {
        // 省
        private String pro;
        // 市
        private String city;
    }
}
